package syscommand

import (
	"errors"
	"strings"
    
    "collecter/app/common/enum"
    "collecter/app/common/helper"
)

type MakeEventListener struct {
	ListenerName string
	BaseCmd
}

func NewMakeEventListener() *MakeEventListener {
	return &MakeEventListener{}
}

func (mel *MakeEventListener) Configure() {
	// fmt.Println("MakeCtl -> Configure")
	mel.StringVar(&mel.ListenerName, "listener", "", "事件监听者名称，可以指定包名")
}

func (mel *MakeEventListener) Execute() error {
	// code ...
	// fmt.Printf("%+v\n", mc)
	if len(mel.ListenerName) == 0 {
		return errors.New("事件监听者名称不能为空")
	}
	path, _, eventListener, parseErr := mel.ParsePathAndPkg(mel.ListenerName, "eventListener")
	if parseErr != nil {
		return parseErr
	}
	filename := path + helper.CamelString(eventListener, false) + ".go"
	// fmt.Println(filename)

	var eventListenerTplStr string

	tplFile := enum.ROOT_DIR + "/console/tpl/eventListener.tpl"
	// fmt.Println("tplFile ========== ", tplFile)

	if err, val := helper.ReadFileContent(tplFile, false); err != nil {
		return err
	} else {
		eventListenerTplStr = val
	}
	// fmt.Println("======= before ======== ", ctlTplStr)

	rootDir := strings.Trim(enum.ROOT_DIR, "/")
	dirs := strings.Split(rootDir, "/")
	// fmt.Println(rootDir)
	// fmt.Printf("=====dirs=========%+v\n", dirs)
	mod := dirs[len(dirs)-1]
	// fmt.Println("=====mod=========", mod, len(dirs))

	eventListenerTplStr = strings.ReplaceAll(eventListenerTplStr, "{{mod}}", mod)
	eventListenerTplStr = strings.ReplaceAll(eventListenerTplStr, "{{eventListenerName}}", eventListener)
	// fmt.Println("========= after ========== ", ctlTplStr)

	if err := helper.WriteToFile(filename, eventListenerTplStr); err != nil {
		return err
	}

	return nil
}
